<?php
/**
 * 用户登陆API
 *
 */
namespace Admin\Controller;

use Think\Controller;
use Common\Controller\_AllController;

class LoginController extends _AllController {
	public function _initialize(){
		parent::_initialize();
		session_start();
      	header('Cache-control:private,must-revalidate');
	}

	public function Index()
	{
		$res = array('rcode'=>0,'data'=>date('Y-m-d H:i:s'),'msg'=>'OK');
		$uinfo = isset($_SESSION[C('ADMIN_HASH_NAME')]) ? $_SESSION[C('ADMIN_HASH_NAME')] : '';
		if( count( $uinfo ) ){
			$uinfos = authcode( $uinfo , "DECODE");
			$arruinfo = unserialize( $uinfos );
			if( $arruinfo && isset( $arruinfo['user_id'])  ){
				$res['rcode'] = 1;
				$res['msg'] = '已经登陆';
				$res['data'] = $arruinfo;
				e_json( $res );
			}
		}
		$username = I('post.username',false,'trim');
		$password = I('post.password',false,'trim');
		if ($password&&strlen($password)>20) {
			$datas = authcode($password, 'DECODE');
			$datas = urldecode($datas);
			$data = unserialize($datas);
			if ($data&&$data['user_id']&&$data['passwd']) {
				$password = $data['passwd'];
			}
		}
		$caption = I('post.caption','');
		if (!$username || !$password) {
			$res['msg'] = "提交参数错误";
		} 
		else {
			$Mu = D("Admin/User");
			$loginres =  $Mu->Login( $username, $password, $caption );
			if ($loginres&&$loginres['r']) {
				$res['data'] = $loginres['d'];
				$res['token'] = authcode($res['data']['user_id'], 'ENCODE');
				//客户端记住密码功能
				$rememberdata = array();
				$rememberdata['user_id'] = $res['data']['user_id'];
				$rememberdata['passwd'] = $password;
				$rememberdata['time'] = time();
				$strRemember = serialize($rememberdata);
				$res['remember'] = urlencode(authcode($strRemember, 'ENCODE')); //URLencode 解决特殊字符问题 
				$stru = serialize( $res['data'] ) ;
				$strsession =  authcode($stru, 'ENCODE');
				$_SESSION[C('ADMIN_HASH_NAME')] = $strsession;
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
			}else{
				$res['msg'] = $loginres['m'];
			}
		}
		/*未登录，访问某模块在session中保存url*/
		$goToURL = I('get.goToURL');
		if($goToURL)
			$_SESSION[C('GO_TO_URL')] = $goToURL;
		$res['goToURL'] = $_SESSION[C('GO_TO_URL')];
		
		e_json( $res );
	}

	/**
	 * 生成图形验证码
	 *
	 * @return img 图像验证码
	 */
	public function caption()
	{
		//
	}

	public function logout(){
		$_SESSION[C('ADMIN_HASH_NAME')] = null;
		$res = array('rcode'=>1,'data'=>date('Y-m-d H:i:s'),'msg'=>'OK');
		echo json_encode( $res );
		exit();
	}

}

?>